package com.ruoyi.common.utils.tt;

/**
 * @Author: TT
 * @Date: 2025/8/19 16:25
 * @Description: ，，
 * @Version: v1.0
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class WeiboSupetopicSigner {
    private final HttpClient httpClient;
    private final String cookie;
    private final Random random;

    public WeiboSupetopicSigner(String cookie) {
        this.httpClient = HttpClients.createDefault();
        this.cookie = cookie;
        this.random = new Random();
    }
    /**
     * 获取超话列表
     */
    public List<JSONObject> getSuperTopicList() throws Exception {
        String url = "https://weibo.com/ajax/profile/topicContent?tabid=231093_-_chaohua";
        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject data = JSON.parseObject(json).getJSONObject("data");
            List<JSONObject> topics = data.getJSONArray("list").toJavaList(JSONObject.class);
            // System.out.println("获取到 " + topics.size() + " 个超话");
            return topics;
        } else {
            throw new Exception("获取超话列表失败: " + response.getStatusLine().getStatusCode());
        }
    }

    /**
     * 单个超话签到
     */
    public boolean signSuperTopic(String topicId, String topicName) throws Exception {
        String url = String.format(
                "https://weibo.com/p/aj/general/button?" +
                        "ajwvr=6&api=http://i.huati.weibo.com/aj/super/checkin&" +
                        "texta=签到&textb=已签到&status=0&id=%s&" +
                        "location=page_%s_super_index&timezone=GMT+0800&" +
                        "lang=zh-cn&plat=Win32&__rnd=%d",
                topicId, topicId, System.currentTimeMillis()
        );

        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        try {
            // 随机延迟1-3秒
            Thread.sleep(1000 + random.nextInt(2000));

            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject json = JSON.parseObject(result);
                if ("100000".equals(json.getString("code"))) {
                    // System.out.println("超话【" + topicName + "】签到成功");
                    return true;
                } else {
                    // System.out.println("超话【" + topicName + "】签到失败: " + json.getString("msg"));
                }
            } else {
                // System.out.println("超话【" + topicName + "】请求失败: " + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            // System.out.println("超话【" + topicName + "】签到异常: " + e.getMessage());
        }
        return false;
    }

    /**
     * 自动签到所有超话（多线程版）
     */
    public void autoSignAllTopics() throws Exception {
        List<JSONObject> topics = getSuperTopicList();
        if (topics.isEmpty()) {
            // System.out.println("没有获取到超话列表");
            return;
        }

        // System.out.println("开始签到 " + topics.size() + " 个超话...");
        // 5个线程并发
        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (JSONObject topic : topics) {
            String oid = topic.getString("oid");
            if (oid != null && oid.startsWith("1022:")) {
                String topicId = oid.split(":")[1];
                String topicName = topic.getString("title");

                executor.submit(() -> {
                    try {
                        signSuperTopic(topicId, topicName);
                    } catch (Exception e) {
                        // System.out.println("超话【" + topicName + "】执行失败: " + e.getMessage());
                    }
                });
            }
        }

        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.MINUTES);
        // System.out.println("所有签到任务已完成");
    }
    /**
     * 自动签到所有超话并返回结果列表（多线程版）
     * @return 签到结果列表，格式为："【超话名】签到成功" 或 "【超话名】今天已签到"
     * @throws Exception 如果获取超话列表失败
     */
    public List<String> autoSignAllTopicsWithResults() throws Exception {
        List<JSONObject> topics = getSuperTopicList();
        List<String> results = Collections.synchronizedList(new ArrayList<>());

        if (topics.isEmpty()) {
            results.add("没有获取到超话列表");
            return results;
        }

        // System.out.println("开始签到 " + topics.size() + " 个超话...");
        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (JSONObject topic : topics) {
            String oid = topic.getString("oid");
            if (oid != null && oid.startsWith("1022:")) {
                String topicId = oid.split(":")[1];
                String topicName = topic.getString("title");

                executor.submit(() -> {
                    try {
                        boolean isSuccess = signSuperTopic(topicId, topicName);
                        String result = isSuccess ?
                                "【" + topicName + "】超话，签到成功" :
                                "【" + topicName + "】超话，小橘子今天已经签到了哦";
                        results.add(result);
                    } catch (Exception e) {
                        String errorMsg = "【" + topicName + "】超话，签到失败: " + e.getMessage();
                        results.add(errorMsg);
                    }
                });
            }
        }

        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.MINUTES);
        // System.out.println("所有签到任务已完成");
        return results;
    }

    /**
     * 设置通用请求头
     */
    private void setCommonHeaders(HttpGet request) {
        request.setHeader("Cookie", cookie);
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0");
        request.setHeader("X-Requested-With", "XMLHttpRequest");
        request.setHeader("Referer", "https://weibo.com/u/page/follow/7935673987/231093_-_chaohua");

        // 从Cookie中提取XSRF-TOKEN
        String[] cookies = cookie.split(";");
        for (String c : cookies) {
            if (c.trim().startsWith("XSRF-TOKEN=")) {
                request.setHeader("X-XSRF-TOKEN", c.split("=")[1]);
                break;
            }
        }
    }
    /**
     * 通过 sideInterested 接口获取当前登录用户的 UID
     * @return 当前用户的 UID（如 7935673987），如果失败返回 null
     * @throws Exception 网络或解析错误
     */
    public Long getCurrentUserId() throws Exception {
        String url = "https://www.weibo.com/ajax/side/cards/sideInterested";
        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject data = JSON.parseObject(json);
            data = data.getJSONObject("data");
            // 直接从返回的JSON中提取uid字段
            return data.getLong("uid");
        } else {
            throw new Exception("获取UID失败: HTTP " + response.getStatusLine().getStatusCode());
        }
    }
    /**
     * 获取用户的所有朋友列表
     * @param uid 用户UID
     * @return 朋友列表的JSONObject集合
     * @throws Exception 网络或解析错误
     */
    public List<JSONObject> getAllFriends(Long uid) throws Exception {
        List<JSONObject> allFriends = new ArrayList<>();
        int page = 1;
        boolean hasMore = true;

        while (hasMore) {
            String url = String.format("https://www.weibo.com/ajax/friendships/friends?page=%d&uid=%d", page, uid);
            HttpGet request = new HttpGet(url);
            setCommonHeaders(request);

            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity());
                JSONObject data = JSON.parseObject(json);

                List<JSONObject> friends = data.getJSONArray("users").toJavaList(JSONObject.class);
                allFriends.addAll(friends);

                // 检查是否还有更多数据
                int total = data.getIntValue("total_number");
                // 每页默认20条
                hasMore = page * 20 < total;
                page++;

                // 添加延迟避免请求过快
                Thread.sleep(1000 + random.nextInt(1000));
            } else {
                throw new Exception("获取朋友列表失败: HTTP " + response.getStatusLine().getStatusCode());
            }
        }

        // System.out.println("共获取到 " + allFriends.size() + " 个朋友");
        return allFriends;
    }
    /**
     * 获取用户的所有粉丝列表（多线程版）
     * @param uid 用户UID
     * @param maxThreads 最大线程数（建议5-10）
     * @return 粉丝列表的JSONObject集合
     * @throws Exception 网络或解析错误
     */
    public List<JSONObject> getAllFollowers(Long uid, int maxThreads) throws Exception {
        // 1. 先获取总粉丝数和页数
        int total = getFollowersTotalCount(uid);
        int totalPages = (int) Math.ceil(total / 20.0);

        // 2. 创建线程池和结果集合
        ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
        List<JSONObject> allFollowers = Collections.synchronizedList(new ArrayList<>());

        // 3. 多线程分页获取
        List<Future<?>> futures = new ArrayList<>();
        for (int page = 1; page <= totalPages; page++) {
            final int currentPage = page;
            Future<?> future = executor.submit(() -> {
                try {
                    List<JSONObject> pageFollowers = getFollowersByPage(uid, currentPage);
                    allFollowers.addAll(pageFollowers);
                    // System.out.println("已获取第 " + currentPage + " 页粉丝，当前总数: " + allFollowers.size());
                } catch (Exception e) {
                    System.err.println("第 " + currentPage + " 页获取失败: " + e.getMessage());
                }
            });
            futures.add(future);
            // 控制请求频率
            Thread.sleep(500 + random.nextInt(1000));
        }

        // 4. 等待所有任务完成
        for (Future<?> future : futures) {
            future.get();
        }
        executor.shutdown();

        return allFollowers;
    }

    /**
     * 获取粉丝总数
     */
    private int getFollowersTotalCount(Long uid) throws Exception {
        String url = String.format("https://www.weibo.com/ajax/friendships/friends?uid=%d&relate=fans&page=1", uid);
        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            return JSON.parseObject(json).getIntValue("total_number");
        }
        throw new Exception("获取粉丝总数失败: HTTP " + response.getStatusLine().getStatusCode());
    }

    /**
     * 分页获取粉丝列表
     */
    private List<JSONObject> getFollowersByPage(Long uid, int page) throws Exception {
        String url = String.format(
                "https://www.weibo.com/ajax/friendships/friends?uid=%d&relate=fans&count=20&page=%d&type=fans",
                uid, page
        );

        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject data = JSON.parseObject(json);
            return data.getJSONArray("users").toJavaList(JSONObject.class);
        }
        throw new Exception("获取粉丝页失败: HTTP " + response.getStatusLine().getStatusCode());
    }
    /**
     * 通过UID获取用户详细信息
     * @param uid 用户UID
     * @return 包含用户详细信息的JSONObject
     * @throws Exception 网络或解析错误
     */
    public JSONObject getUserInfoByUid(Long uid) throws Exception {
        String url = String.format("https://weibo.com/ajax/profile/info?uid=%d", uid);
        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(json);
            JSONObject data = jsonObject.getJSONObject("data");

            if (data != null) {
                JSONObject user = data.getJSONObject("user");
                if (user != null) {
                    // 直接返回整个user对象
                    return user;
                }
            }
            throw new Exception("用户数据解析失败");
        } else {
            throw new Exception("获取用户信息失败: HTTP " + response.getStatusLine().getStatusCode());
        }
    }
    /**
     * 根据微博昵称获取用户UID
     * @param name 微博昵称
     * @return 用户UID，如果未找到返回null
     * @throws Exception 网络或解析错误
     */
    public Long getUidByName(String name) throws Exception {
        // 编码昵称，处理特殊字符
        String encodedName = java.net.URLEncoder.encode(name, "UTF-8");
        String url = "https://weibo.com/ajax/side/search?q=" + encodedName;

        HttpGet request = new HttpGet(url);
        setCommonHeaders(request);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject data = JSON.parseObject(json).getJSONObject("data");

            // 解析用户列表
            List<JSONObject> users = data.getJSONArray("user").toJavaList(JSONObject.class);
            if (!users.isEmpty()) {
                // 返回第一个匹配用户的UID
                return users.get(0).getLong("uid");
            }
        }
        return null;
    }



    public static void main(String[] args) throws Exception {
        // 示例用法
        String cookie = "SCF=Al2doT1S5ee7BtnVo8QbdJGMEDJHVQ_jkl5wW1G7XGvz2rlYBCZKoG8kNcHHsMzmCEcl9_H6Cz5_10ZpmGMfoDY.; SINAGLOBAL=2656921181567.2876.1747302505906; SUB=_2A25FoTfRDeRhGeFH6FcX9y3FwzuIHXVm3zUZrDV8PUNbmtAbLXilkW9Ne3QZFmwkEP7e7WWtFfTfd_vCmJdUvdnL; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFZu5qWi4gcc-8AG83fN4-I5JpX5KzhUgL.FoM4e0-cS0e41hM2dJLoIEXLxKqL12-L12qLxKMLBoeL1KqLxKMLB.zL1K.LxK-LBo5L12qLxK.L1--LBK5t; ALF=02_1758254209; webim_unReadCount=%7B%22time%22%3A1755683274437%2C%22dm_pub_total%22%3A0%2C%22chat_group_client%22%3A1062%2C%22chat_group_notice%22%3A1%2C%22allcountNum%22%3A1087%2C%22msgbox%22%3A0%7D; XSRF-TOKEN=aJJnHjtg5xXtJN7bUqAMT_Vi; WBPSESS=9kYNdICtC49BZxwXfZ0tFF_luQ0zykMaFhS2oOsI92mUgWHsg7M9k9Y4qVd1qyCqFN7-ulivVEyLv1tVVoX_o_OnUhuwS5nzkr8tjPzECf7djtcVm80ldelSrl8Cvi0Q29TI-dOiCrS-at8mLbRDvg==; _s_tentry=yuanbao.tencent.com; UOR=,,yuanbao.tencent.com; Apache=8173768279144.831.1755746891816; ULV=1755746891818:4:3:3:8173768279144.831.1755746891816:1755658975909";
        WeiboSupetopicSigner signer = new WeiboSupetopicSigner(cookie);
        // 获取当前用户ID
        //Long uid = signer.getCurrentUserId();
        //// 获取所有朋友列表
        //List<JSONObject> friends = signer.getAllFriends(uid);
        //for (JSONObject friend : friends) {
        //    // System.out.println(friend.getString("name") + " - " + friend.getString("id"));
        //}
        //System.out.println(signer.getCurrentUserId());
        //System.out.println(signer.getSuperTopicList());
        //signer.autoSignAllTopics();
        // 获取所有粉丝（使用5个线程）
        //List<JSONObject> followers = signer.getAllFollowers(uid, 5);
        //System.out.println("共获取粉丝数: " + followers.size());
        //
        //// 打印前10个粉丝
        //followers.stream().limit(10).forEach(f -> {
        //    // System.out.println(f.getString("screen_name") + " (ID:" + f.getLong("id") + ")");
        //});
        //JSONObject userInfo = signer.getUserInfoByUid(3669102477L);
        // System.out.println(userInfo);
        System.out.println(signer.getUidByName("王一博"));


    }
}
